package cn.kgm.makeGodV2.ruleEngine;

import java.util.HashMap;
import java.util.Map;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-9-24 17:54
 * @Description: cn.kgm.makeGodV2.ruleEngine.SingleItemCheckRule
 */
public class SingleItemCheckRule implements RuleStrategy<Boolean> {
    @Override
    public String getRuleType() {
        return "SINGLE_ITEM_CHECK";
    }

    @Override
    public boolean validate(RuleContext context) {
        ConditionConfig config = context.getParam("conditionConfig", ConditionConfig.class);
        return config != null && config.getValue() != null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public RuleResult<Boolean> execute(RuleContext context) {
        try {
            ConditionConfig config = context.getParam("conditionConfig", ConditionConfig.class);
            Map<String, Integer> requiredItem = (Map<String, Integer>) config.getValue();
            Map<String, Integer> playerItems = context.getParam("playerItems", Map.class);

            if (playerItems == null) playerItems = new HashMap<>();

            for (Map.Entry<String, Integer> entry : requiredItem.entrySet()) {
                String itemId = entry.getKey();
                int requiredCount = entry.getValue();
                int playerCount = playerItems.getOrDefault(itemId, 0);

                if (playerCount >= requiredCount) {
                    String message = String.format("拥有%s %d个(需要%d个)", itemId, playerCount, requiredCount);
                    return RuleResult.success(message, true);
                }
            }

            // 如果没有满足条件的物品
            Map.Entry<String, Integer> entry = requiredItem.entrySet().iterator().next();
            String message = String.format("缺少%s，需要%d个", entry.getKey(), entry.getValue());
            return RuleResult.success(message, false);

        } catch (Exception e) {
            return RuleResult.fail("单个物品检查失败: " + e.getMessage());
        }
    }
}
